<template>
  <div v-show="show" class="main">
    <div class="main-top">
      <Container class="main-l" display="flexY">
        <el-form ref="ruleForm" :model="ruleForm" size="mini" :inline="true">
          <el-form-item prop="configurationId">
            <el-select v-model="ruleForm.configurationId" placeholder="请选择" @change="codeSearch">
              <el-option v-for="(item,index) in convey.attributeConfiguration" :key="index" :label="item.attributeName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="parameterName">
            <el-input v-model="ruleForm.parameterName" placeholder="请输入参数名称" @keyup.enter.native="codeSearch" />
          </el-form-item>
        </el-form>
        <Table
          v-if="ruleForm.configurationId"
          :columns="tableColumns"
          :data="tableData"
          :loading="tableLoading"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize
          }"
          :show-header="false"
          row-key="id"
          :default-expand-all="false"
          :tree-props="{children: 'childrenList', hasChildren: 'hasChildren'}"
          layout="total, prev, pager, next, sizes"
          @paginationChange="pageChange"
          @rowClick="rowClick"
        />
      </Container>
      <Container class="main-r" display="flexY">
        <span class="fh-span">符号</span>
        <el-row>
          <el-button v-for="(item, index) in convey.logicalSymbols" :key="index" size="mini" :title="item.value" plain @click="add(item)">{{ item.label }}</el-button>
        </el-row>
        <span v-if="!type" class="fh-span">插入数值</span>
        <el-row v-if="!type" :gutter="8">
          <el-col :span="18">
            <el-input v-model="interpolation" size="mini" placeholder="请输入数值" />
          </el-col>
          <el-col :span="4">
            <Button @click="handlerInsert">插入</Button>
          </el-col>
        </el-row>
      </Container>
    </div>
  </div>
</template>
<script>
import { attributeDataPage } from '../api/indicatorLibrary'
export default {
  name: 'RuleItem', // 公式弹框
  props: {
    type: Number,
    show: {
      type: Boolean,
      default: false
    },
    convey: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      interpolation: '',
      assemblyObj: {},
      turn: '',
      tableColumns: [{
        dataIndex: 'label'
      }],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableLoading: false,
      ruleForm: {
        ruleDrugFormula: '',
        ruleFormula: '',
        parameterName: '',
        configurationId: '',
        ruleTypeName: ''
      },
      ruleBaseFormula: {
        items: [],
        symbolList: ''
      },
      choseParamCurrent: {} // 选中的参数
    }
  },
  watch: {
    // 公式最终数据格式 传给父组件
    'ruleForm.ruleFormula': {
      handler(value) {
        this.ruleBaseFormula.symbolList = this.turn
        this.assemblyObj = { ...this.ruleBaseFormula, items: this.ruleBaseFormula.items.filter(item => item['code'] !== undefined) }
        this.$emit('changeRule', value, this.assemblyObj)
        // const { items, list } = this.ruleBaseFormula
        // const separators = list.split('')
        // const arr = []
        // let num = 0
        // separators.forEach((item, index) => {
        //   if (item === '$') {
        //     arr.push(items[num])
        //     num++
        //   } else {
        //     const obj = {
        //       value: '',
        //       code: item
        //     }
        //     arr.push(obj)
        //   }
        // })
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {},
  methods: {
    // 插入数值
    handlerInsert() {
      if (this.interpolation) {
        this.insertFormula({
          obj: {
            code: 'insertNumber',
            value: this.interpolation,
            label: this.interpolation
          }
        })
      }
    },
    // 点击插入具体table中属性
    rowClick(val) {
      this.insertFormula({
        obj: {
          ...val,
          code: val.configurationId
        }
      })
    },
    // 插入符号
    add(val) {
      if (val.label === 'CE') {
        // 清除符号
        this.turn = this.turn.slice(0, -1)
        this.ruleBaseFormula.items.pop()
      } else {
        this.ruleBaseFormula.items.push(val)
        this.turn = this.turn + val.label
      }
      this.ruleForm.ruleFormula = this.ruleBaseFormula.items.map(item => item.label).join('') || ''
    },
    // 所需公式数据格式处理
    insertFormula({ obj }) {
      if (this.turn.endsWith('$')) {
        return this.showMessage()
      }
      this.turn += '$'
      const { code, label, value } = { ...obj }
      const item = { code, label, value }
      this.ruleBaseFormula.items.push(item)
      this.ruleForm.ruleFormula = this.ruleBaseFormula.items.map(item => item.label).join('') || ''
    },
    // 操作错误提示
    showMessage(msg) {
      this.$message.warning(msg || '格式错误，属性不能和属性连在一起')
    },
    hunrfor() {
      this.tableLoading = true
      const params = {
        configurationId: this.ruleForm.configurationId,
        parameterName: this.ruleForm.parameterName,
        isConfiguration: this.choseParamCurrent?.isConfiguration,
        current: this.currentPage,
        size: this.pageSize
      }
      if (this.type === 1 || this.type === 2) { // 从属性配置（可配置、条件配置跳转的页面）
        params.pageType = 1
      }
      attributeDataPage(params).then((res) => {
        if (res.code === 200) {
          this.tableLoading = false
          if (this.choseParamCurrent?.isConfiguration === 2) {
            this.tableColumns = [{
              dataIndex: 'showName'
            }]
          } else {
            this.tableColumns = [{
              dataIndex: 'label'
            }]
          }
          this.tableData = res.data.list
          this.total = res.data.total
        } else {
          this.tableLoading = false
          this.$message.error(res.msg)
        }
      })
    },
    codeSearch() {
      if (!this.ruleForm.configurationId) {
        return this.showMessage('请先选择左侧参数！')
      }
      this.choseParamCurrent = this.convey.attributeConfiguration.find(item => item.id === this.ruleForm.configurationId)
      this.currentPage = 1
      this.hunrfor()
    },
    handleFormulaCancel() {
      // 初始化所有数据
      Object.assign(this.$data, this.$options.data())
    },
    pageChange(payload) {
      this.currentPage = payload.current
      this.pageSize = payload.pageSize
      this.hunrfor()
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/ .el-pagination {
    overflow-x: auto;
  }
  .main {
      height: 100%;
      min-height: 350px;
      box-shadow: 0px 1px 5px #ddd;
    }

  .main-top {
    display: flex;
    height: 100%;
    justify-content: space-around;
    box-sizing: border-box;

    .main-l {
      width: 500px;
      overflow: hidden;
      box-shadow: 0px 1px 5px #ddd;
      border: 1px solid #DCDFE6;
      margin-right: 10px;
    }

    .main-r {
      flex: 1;
      overflow-y: auto;
      box-shadow: 0px 1px 5px #ddd;
      border: 1px solid #DCDFE6;
      min-width: 300px;

      .el-button {
        width: 50px;
        margin-right: 10px;
        margin-bottom: 10px;
        margin-left: 0;
      }
      .fh-span {
        font-size: 15px;
        font-weight: 600;
        color: #333333;
        line-height: 20px;
        padding-bottom: 10px;
        position: relative;
        padding-left: 10px;
          &::before {
            content: "";
            width: 2px;
            height: 20px;
            background: #217dfa;
            border-radius: 2px;
            position: absolute;
            left: 0px;
            top: 0px;
          }
      }
    }
    /deep/.el-table__body tr:hover>td{
      background-color: #e1e7f0!important;
      cursor: pointer;
    }
  }
</style>
